<?php
// 模型基础类
namespace core\db;

use core\db\Database;
use core\db\Relation;

class Model {
    use Relation;
    // 表名
    protected static $tableName = '';
    // 主键
    protected static $primaryKey = 'id';
    // 数据库连接实例
    protected $db;

    // 构造函数
    public function __construct() {
        // 获取数据库连接
        $this->db = Database::getInstance()->getConnection();
    }

    // 查找单条记录
    public static function find($id) {
        $db = Database::getInstance()->getConnection();
        $table = static::$tableName;
        $primaryKey = static::$primaryKey;

        $stmt = $db->prepare("SELECT * FROM {$table} WHERE {$primaryKey} = ?");
        $stmt->execute([$id]);
        $result = $stmt->fetch();

        // 如果找到记录，返回模型实例
        if ($result) {
            $model = new static();
            foreach ($result as $key => $value) {
                $model->{$key} = $value;
            }
            return $model;
        }

        return null;
    }

    // 查找所有记录
    public static function findAll($conditions = [], $orderBy = '', $limit = '') {
        $db = Database::getInstance()->getConnection();
        $table = static::$tableName;

        $sql = "SELECT * FROM {$table}";
        $params = [];

        // 添加条件
        if (!empty($conditions)) {
            $sql .= " WHERE ";
            $whereClauses = [];
            foreach ($conditions as $field => $value) {
                $whereClauses[] = "{$field} = ?";
                $params[] = $value;
            }
            $sql .= implode(' AND ', $whereClauses);
        }

        // 添加排序
        if (!empty($orderBy)) {
            $sql .= " ORDER BY {$orderBy}";
        }

        // 添加限制
        if (!empty($limit)) {
            $sql .= " LIMIT {$limit}";
        }

        $stmt = $db->prepare($sql);
        $stmt->execute($params);
        return $stmt->fetchAll();
    }

    // 插入记录
    public function insert($data) {
        $table = static::$tableName;
        $fields = implode(', ', array_keys($data));
        $placeholders = implode(', ', array_fill(0, count($data), '?'));

        $stmt = $this->db->prepare("INSERT INTO {$table} ({$fields}) VALUES ({$placeholders})");
        $stmt->execute(array_values($data));
        return $this->db->lastInsertId();
    }

    // 更新记录
    public function update($id, $data) {
        $table = static::$tableName;
        $primaryKey = static::$primaryKey;
        $setClauses = [];
        $params = [];

        foreach ($data as $field => $value) {
            $setClauses[] = "{$field} = ?";
            $params[] = $value;
        }
        $params[] = $id;

        $stmt = $this->db->prepare("UPDATE {$table} SET " . implode(', ', $setClauses) . " WHERE {$primaryKey} = ?");
        return $stmt->execute($params);
    }

    // 删除记录
    public function delete($id) {
        $table = static::$tableName;
        $primaryKey = static::$primaryKey;

        $stmt = $this->db->prepare("DELETE FROM {$table} WHERE {$primaryKey} = ?");
        return $stmt->execute([$id]);
    }

    /**
     * Get the primary key for the model
     * @return string The primary key field name
     */
    public static function getPrimaryKey() {
        return static::$primaryKey;
    }

    /**
     * Get the table name for the model
     * @return string The table name
     */
    public static function getTableName() {
        return static::$tableName;
    }

    /**
     * 获取查询构建器实例
     * @return QueryBuilder
     */
    public static function query() {
        return new QueryBuilder(static::getTableName());
    }
}